#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "TM1637.h"



int segdata[10] = {63,6,91,79,102,109,125,7,127,111};

void tm1637_start()
{
    digitalWrite(CLK,HIGH);
    usleep(140);
    digitalWrite(DIO,HIGH);
    usleep(140);
    digitalWrite(DIO,LOW);
    usleep(140);
    digitalWrite(CLK,LOW);
    usleep(140);
}

void tm1637_stop()
{
    //在CLK处于高电平下,DIO从低升到高 表示结束
  
    digitalWrite(CLK,LOW);
    usleep(140);
    digitalWrite(DIO,LOW);
    usleep(140);
    digitalWrite(CLK,HIGH);
    usleep(140);
    digitalWrite(DIO,HIGH);
    usleep(140);
}

void write_bit(char bit) //写位
{
    digitalWrite(CLK,LOW);
    usleep(140);
    digitalWrite(DIO,bit);
    usleep(140);
    digitalWrite(CLK,HIGH);
    usleep(140);
}

void write_byte(char data) //写字节
{
    for(int i =0;i<8;i++)
    {
        write_bit((data>>i)&0x01);
    }
    digitalWrite(CLK,LOW);
    usleep(140);
    digitalWrite(DIO,HIGH);
    usleep(140);
    pinMode(DIO,INPUT);
    usleep(140);
    digitalWrite(CLK,HIGH);
    while(digitalRead(DIO) == HIGH);
    pinMode(DIO,OUTPUT);
}

void write_command(char cmd) //写命令
{
    tm1637_start();
    write_byte(cmd);
    tm1637_stop();
}

void write_data(char addr,char data)    //写值
{
    tm1637_start();
    write_byte(addr);
    write_byte(data);
    tm1637_stop();
}

void display(int n1,int n2,int n3,int n4)
{
    write_command(64) ;//命令-数据写入寄存器
    write_command(68) ;//命令-固定地址设置方法
    //输入数据
    write_data(192,segdata[n1]);
    write_data(193,segdata[n2]+128);
    write_data(194,segdata[n3]);
    write_data(195,segdata[n4]);
    //打开显示
    write_command(136);//命令-开启显示
}

void nodisplay()
{
    write_command(64) ;//命令-数据写入寄存器
    write_command(68) ;//命令-固定地址设置方法
    //输入数据
    write_data(192,0);
    write_data(193,0);
    write_data(194,0);
    write_data(195,0);
    //打开显示
    write_command(128);//命令-开启显示
}
/*
int main()
{
    if(wiringPiSetupGpio()<0)
    {
        printf("初始化引脚失败\n");
        return 1;
    }

    pinMode(DIO,OUTPUT);
    pinMode(CLK,OUTPUT);

    int i =0;
    while(1)
    {
        //TODO:命令-设置显示数据
        write_command(64) ;//命令-数据写入寄存器
        write_command(68) ;//命令-固定地址设置方法
        //TODO:输入数据
        write_data(192,segdata[i++]);
        i%=10;
        write_data(193,segdata[i++]);
        i%=10;
        write_data(194,segdata[i++]);
        i%=10;
        write_data(195,segdata[i++]);
        i%=10;
        //TODO:打开显示
        write_command(136);//命令-开启显示
        sleep(1);
    }
    return 0;
}
*/